<template>
        <div class="dahezia">
            <el-breadcrumb separator-class="el-icon-arrow-right">
                <el-breadcrumb-item >🏠</el-breadcrumb-item>
                <el-breadcrumb-item>血糖</el-breadcrumb-item>
            </el-breadcrumb>
            <div class="hezia">
                <div class="tip">
                    tips:测量血糖前，请空腹8-12小时哦！其余时段与以下测量标准结果有差异哦！
                </div>
                <div class="tianxiekuan" v-if="!flag" >
                        <el-form ref="form" :model="form" :rules="rules" label-width="50px" >
                            <el-form-item  >
                                <el-input  v-model="form.bloodGlucose"  placeholder="请填写今日血糖值" />
                            </el-form-item>
                        </el-form>
                        <el-button type="primary"  @click="submitForm" size="mini" style="height: 30px; margin-top: 5px">确定</el-button>
                    </div>

                <div class="chartkuang">
                    <div class="mod-demo-echarts">
                        <div ref="chartLineBoxDom" id="chartLineBox" class="chart-box" style="width: 70vw;height: 55vh;"></div>
                    </div>
                </div>
            </div>
        </div>
</template>

<script>
    export default {
        name:  "xuetang" ,
        data() {
            return {
                //请求后端
                userId: null,
                date: [],
                bloodSugar: ['0.0','0.0','0.0','0.0','0.0','0.0',''],
                chartData:[],
                arr: [],
                flag: 0,
                // 表单参数
                form:{
                },
                // 表单校验
                rules: {
                },
            };
        },
        mounted() {
            this.getUser();
            setTimeout(() => {
            this.getLine();
            }, 500);
            //这是为了解决请求异步问题
            setTimeout(() => {
                this.initChartPie();
            }, 1000);
        },
        created() {

        },
        methods: {
            /** 填写血糖按钮 */
            submitForm() {
                const token = sessionStorage.getItem("token");
                this.$http.defaults.headers.common['Authorization'] = token;
                console.log(this.form)
                this.$http.post('bloodSugar', this.form).then(response => {
                    if (response.data.code === 200) {
                        this.$message({showClose: true, message: "填写成功", type: "success"})
                        this.arr = [];
                        this.getLine();
                        //这是为了解决请求异步问题
                        setTimeout(() => {
                            this.initChartPie();
                        }, 1000);
                        this.flag=!this.flag;
                    }
                });
            },
            getBeforeDate(n) {
                console.log(n);//
                let d = new Date();
                let year = d.getFullYear();   // eslint-disable-line no-unused-vars
                let mon = d.getMonth() + 1;
                let day = d.getDate();
                if(day <= n) {
                    if(mon > 1) {
                        mon = mon - 1;
                    } else {
                        year = year - 1;
                        mon = 12;
                    }
                }
                d.setDate(d.getDate() + n); //很重要，+n取得是前一天的时间
                year = d.getFullYear();
                mon = d.getMonth() + 1;
                day = d.getDate();
                return (year+"-"+(mon < 10 ? ('0' + mon) : mon) + "-" + (day < 10 ? ('0' + day) : day));
            },
            getUser(){
                 this.$http.get('user/info',{headers:{
                        'Authorization':window.sessionStorage.getItem('token')
                    }}).then(jiegugo=> {
                     this.userId=jiegugo.data.data.basicUserInformation.id;
                     console.log("用户id="+this.userId);
                })

            },
            getDate(){
                for(let i=0 ; i > -7; i--) {
                    this.arr.push(this.getBeforeDate(i));
                }
            },
            getLine() {
                this.getDate();
                console.log(this.arr);
                console.log("用户id="+this.userId);
                    const token = sessionStorage.getItem("token");
                    this.$http.defaults.headers.common['Authorization'] = token;
                     this.$http.get('bloodSugar/select7dayList?userId='+this.userId).then( response =>{
                         this.chartData =  response.data.data.list;
                         this.flag =  response.data.data.flag;
                        console.log(this.chartData);
                        console.log(this.chartData[0].time);
                        console.log(this.arr[0]);
                     for(let k=0;k<7;k++){
                        for(let j=0;j<this.chartData.length;j++){
                            if(this.arr[k] == this.chartData[j].time){
                                this.bloodSugar[7-k] = this.chartData[j].bloodGlucose;
                                break;
                            }
                        }
                    }
                    console.log(this.arr);
                    console.log(this.bloodSugar);
                });
            },
            initChartPie() {
                this.chartLine = this.$echarts.init(this.$refs.chartLineBoxDom)
                // 指定图表的配置项和数据
                var option = {
                    title:{
                        text: '近七天的血糖值',
                        x: "700",
                        },
                    tooltip: {              //设置tip提示
                        trigger: 'axis'
                    },
                    legend: {               //设置区分（哪条线属于什么）
                        data:['血糖值']
                    },

                    // color: ['#8AE09F'],       //设置区分（每条线是什么颜色，和 legend 一一对应）
                    xAxis: {                //设置x轴
                        type: 'category',
                        name: '日期',
                        data: this.arr.reverse(),
                        nameGap: 7,//坐标轴名称与轴线之间的距离。
                        axisTick: {//是否显示坐标轴刻度。
                            inside: true//坐标轴刻度是否朝内，默认朝外。
                        },
                        axisLabel:{interval: 0}

                    },
                    yAxis: {
                        type: 'value',
                        name: '血糖值(mmol/L)',
                        splitLine: {
                            show: false//是否显示分隔线。默认数值轴显示，类目轴不显示。
                        },
                        nameGap: 15,
                        axisTick: {
                            inside: true
                        },
                        axisLine: {
                            show: true
                        },
                    },
                    grid:{
                        left: 100,
                        top: 100,
                        y2: 100,
                        x2: 50
                    },
                    visualMap: [ // 分段标记，如图中折线红色部分
                        {
                            show: false,
                            type: 'piecewise',
                            seriesIndex: 0, //控制series 对应的区域
                            pieces: [
                                {
                                    gt: 7.0, // 数据大于50
                                    color: '#DC143C'
                                },
                                {
                                    gt: 3.1,
                                    lte: 6.1,

                                    color: '#67c23a '    //安全

                                },{
                                    gt: 6.1,
                                    lte: 7.0,
                                    color: '#e6a23c'
                                },{
                                    gt: 2.8,
                                    lte: 3.1,
                                    color: '#e6a23c'
                                },{
                                    lte: 2.8, // 数据大于50
                                    color: '#DC143C'
                                },
                            ]
                        }
                    ],
                    series: [
                        {
                            name: '血糖值',
                            data:  this.bloodSugar,
                            type: 'line',               // 类型为折线图
                            symbol: 'circle',//标记的类型：圆圈
                            itemStyle: {
                                normal: {
                                    shadowBlur: 50,//文字块的背景阴影长度。
                                    shadowColor: 'black',//文字块的背景阴影颜色。
                                    color: 'black',//图形的颜色
                                }
                            },
                            showSymbol: false,
                            markLine: {// 如图中红色标记线
                                    silent: true,
                                    symbol: false, // 不显示标记线两端端点符号
                                    lineStyle: {
                                        color: '#DC143C'
                                    },
                                    data: [
                                        {
                                            yAxis: 7.0
                                        },
                                        {
                                            yAxis: 2.8
                                        }
                                    ],
                                    label: {
                                        show: true
                                    }
                                },
                        }
                    ],
                };
                this.chartLine.setOption(option);
                // 如果浏览器缩放重新渲染图表
                window.addEventListener("resize", function () {
                    if (this.chartLine) {
                        this.chartLine.resize();
                    }
                });
            },
        },
    };
</script>

<style lang="scss">

    .dahezia{
        padding-top: 3px;
        height: 600px;
        background-color: #fffacd;
    }
    .hezia{
        width: 80%;
        margin-left: 10%;
        margin-top: 3%;
        height: 500px;
        /*display: flex;*/
        justify-content:center;
        background: white;
        color: black;
    }
    .tip{
        width: 100%;
        height: 20px;
        font-size: 16px;
        color: red;
    }
    .tianxiekuan{
        width: 100%;
        height: 50px;
        font-size: 12px;
        margin-top: 15px;
        display: flex;
        text-align: center;
    }
    .chartkuang{
        font-size: 30px;
    }
    .mod-demo-echarts {
        > .el-alert {
            margin-bottom: 10px;
        }
        > .el-row {
            margin-top: -10px;
            margin-bottom: -10px;

            .el-col {
                padding-top: 10px;
                padding-bottom: 10px;
            }
        }
        .chart-box {
            min-height: 150px;
            min-width: 700px;
            margin-left: 50px;
        }
    }
    .dahezi{
        padding-top: 3px;
        height: 600px;
        background-color: #fffacd;
    }
    .hezi{
        width: 80%;
        margin-left: 10%;
        margin-top: 3%;
        height: 500px;
        /*display: flex;*/
        justify-content:center;
        background: white;
        color: black;
    }
</style>
